using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
//using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace BostonAzureSite
{
    public class WebRole : RoleEntryPoint
    {
        public override bool OnStart()
        {
            StartDiagnostics();

            //need to sleep for 3 seconds until Diagnostics startup // TODO: how do we know 3 second delay is (a) sufficient, (b) necessary
            System.Threading.Thread.Sleep(3000);
            // Shows up in table WADLogsTable in bostonazureops (whether running from Azure Cloud or local Dev Fabric Compute Emulator)
  //          Logger.Write("Starting Boston Azure Web Role", "General");

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
            RoleEnvironment.Changing += RoleEnvironmentChanging;

            //required before accessing cloud storage
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
            });

            return base.OnStart();
        }

        public override void OnStop()
        {
            //Logger.Write("Stopping Boston Azure Web Role", "General");

            base.OnStop();
        }

        private void StartDiagnostics()
        {
            // Get default initial configuration.
            var config = DiagnosticMonitor.GetDefaultInitialConfiguration();

            config.Logs.ScheduledTransferLogLevelFilter = LogLevel.Undefined;
            config.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(5);

            config.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
            config.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(5);
            config.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(5);

            // Start the diagnostic monitor with the modified configuration.
            DiagnosticMonitor.Start("DiagnosticsConnectionString", config);
        }

        private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
        {
            // If a configuration setting is changing
            if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
            {
                // Set e.Cancel to true to restart this role instance
                e.Cancel = true;
            }
        }
    }
}
